<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { getOrderList, updateOrderStatus, initSocket, onOrderCreated, offOrderCreated, onUserStatusChanged, offUserStatusChanged, onNewAnnouncement, offNewAnnouncement, onNewOrder, offNewOrder, onOrderStatusChanged, offOrderStatusChanged } from '../api/auth'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'

const orders = ref([])
const detailDialogVisible = ref(false)
const detailOrder = ref<any>({})

const formatDate = (dateStr: string) => {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  const pad = (n: number) => n.toString().padStart(2, '0')
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
}

const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
const userStatus = ref('正常')
const isUserNormal = ref(true)
const pageError = ref('')

const fetchOrders = async () => {
  try {
    const userId = userInfo._id
    const res = await getOrderList({ userId })
    if (res.data.code === 200) {
      orders.value = res.data.data
      isUserNormal.value = true
      pageError.value = ''
    }
  } catch (e: any) {
    if (e.response && e.response.status === 403) {
      isUserNormal.value = false
      pageError.value = e.response.data.message || '当前账号状态异常，无法进行订单管理操作，请联系管理员。'
    }
  }
}

const handleViewDetail = (row: any) => {
  if (!isUserNormal.value) return
  detailOrder.value = row
  detailDialogVisible.value = true
}

// 订单状态选项
const orderStatusOptions = [
  { label: '待发货', value: '待发货' },
  { label: '待收货', value: '待收货' },
  { label: '退款', value: '退款' }
]

const quickUpdateStatus = async (row: any, newStatus: string) => {
  try {
    await updateOrderStatus(row._id, newStatus)
    ElMessage.success('订单状态已更新')
    fetchOrders()
  } catch (e) {
    ElMessage.error('订单状态更新失败')
  }
}

onMounted(() => {
  fetchOrders()
  // 初始化 Socket.IO 连接
  if (userInfo._id) {
    initSocket(userInfo._id)
    
    // 监听订单创建事件
    onOrderCreated((data: any) => {
      ElNotification({
        title: '新订单提醒',
        message: data.message,
        type: 'success',
        duration: 5000
      })
      fetchOrders()
    })
    
    // 监听所有新订单事件（移动端下单推送）
    onNewOrder((order: any) => {
      ElNotification({
        title: '新订单提醒',
        message: `有新订单：${order.name}，金额：${order.price}`,
        type: 'success',
        duration: 5000
      })
      fetchOrders()
    })
    
    // 监听用户状态变更事件
    onUserStatusChanged((data: any) => {
      if (data.userId === userInfo._id) {
        // 更新本地状态
        if (data.status === '已冻结') {
          isUserNormal.value = false
          pageError.value = data.message
          ElMessage.error(data.message)
        } else if (data.status === '正常') {
          isUserNormal.value = true
          pageError.value = ''
          ElMessage.success(data.message)
          // 重新获取数据
          fetchOrders()
        }
      }
    })
    
    // 监听新公告事件
    onNewAnnouncement((data: any) => {
      ElNotification({
        title: '新公告',
        message: data.message,
        type: 'info',
        duration: 5000
      })
    })

    onOrderStatusChanged((data: { _id: string, status: string }) => {
      if (data.status === '已收货') {
        ElNotification({
          title: '订单状态变更',
          message: `订单 ${data._id} 已收货`,
          type: 'success'
        });
        fetchOrders();
      }
    });
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  offOrderCreated()
  offUserStatusChanged()
  offNewAnnouncement()
  offNewOrder()
  offOrderStatusChanged();
})
</script>

<template>
  <div class="order-container">
    <div v-if="!isUserNormal">
      <el-card style="margin: 60px auto; max-width: 480px; text-align: center; color: #e1251b; font-size: 1.2rem;">
        <el-icon style="font-size: 2.5rem; margin-bottom: 12px;"><WarningFilled /></el-icon>
        <div>{{ pageError || '当前账号状态异常，无法进行订单管理操作，请联系管理员。' }}</div>
      </el-card>
    </div>
    <div v-else>
      <el-card>
        <template #header>
          <span>订单管理</span>
        </template>
        <el-table :data="orders" border stripe style="width: 100%;">
          <el-table-column prop="_id" label="订单编号"  />
          <el-table-column prop="name" label="客户" />
          <el-table-column prop="date" label="下单时间">
            <template #default="scope">
              {{ formatDate(scope.row.date) }}
            </template>
          </el-table-column>
          <el-table-column prop="price" label="金额" >
            <template #default="scope">
              ￥{{ scope.row.price }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" >
            <template #default="scope">
              <el-tag :type="scope.row.statusType">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" >
            <template #default="scope">
              <template v-if="scope.row.status === '待收货'">
                <el-button type="primary" link size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
              </template>
              <template v-else-if="scope.row.status === '待发货'">
                <el-button type="primary" link size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
                <el-button type="success" link size="small" @click="quickUpdateStatus(scope.row, '已发货')">发货</el-button>
              </template>
              <template v-else-if="scope.row.status === '退款'">
                <el-button type="danger" link size="small" @click="quickUpdateStatus(scope.row, '已退款')">退款</el-button>
                <el-button type="warning" link size="small" @click="quickUpdateStatus(scope.row, '拒绝退款')">拒绝退款</el-button>
                <el-button type="primary" link size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
              </template>
              <template v-else>
                <el-button type="primary" link size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog v-model="detailDialogVisible" title="订单详情" width="500px">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="订单编号">{{ detailOrder._id }}</el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ detailOrder.name }}</el-descriptions-item>
          <el-descriptions-item label="商品描述">{{ detailOrder.description }}</el-descriptions-item>
          <el-descriptions-item label="单价">￥{{ detailOrder.price }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">￥{{ detailOrder.orderAmount }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detailOrder.status }}</el-descriptions-item>
          <el-descriptions-item label="标签">{{ detailOrder.Tabs }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ detailOrder.date ? formatDate(detailOrder.date) : '' }}</el-descriptions-item>
          <el-descriptions-item label="商品图片">
            <el-image v-if="detailOrder.image" :src="detailOrder.image" style="width:60px;height:60px;" fit="cover" />
          </el-descriptions-item>
        </el-descriptions>
        <template #footer>
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.order-container {
  padding: 24px;
}
</style>